import { SimplPool } from "../pool/SimplPool";


export default class FunListener {

    private static readonly pool: SimplPool<FunListener> = new SimplPool<FunListener>({
        createHandler: () => {
            return new FunListener();
        },

        destroyHandler: (item: FunListener) => {
            item.destroy();
        },

        showHandler: (item: FunListener) => {

        },

        hideHandler: (item: FunListener) => {
            item['clear'];
        }
    });

    public static create(callback: Function, target?: any): FunListener {
        let listener: any = FunListener.pool.spawn();
        listener.setListener(callback, target);
        return listener;
    }

    private _callback!: Function | null;
    private _target!: any;

    public setListener(callback: Function, target: any) {
        this._callback = callback;
        this._target = target;
    }

    public run(...agrs: any[]) {
        if (this._callback) {
            if (this._target) {
                this._callback.call(this._target, ...agrs);
            }
            else {
                this._callback.call(this, ...agrs);
            }
        }
    }

    public runOne(...agrs: any[]) {
        this.run(...agrs);
        FunListener.pool.recycle(this);
    }

    public destroy() {
        this.clear();
        FunListener.pool.recycle(this);
    }

    private clear() {
        this._callback = null;
        this._target = null;
    }
}